package services

import (
	"go_ruoyi/model/db_model"

	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)

// 树形菜单
type Mate struct {
	Icon    string `json:"icon"`
	Link    string `json:"link"`
	NoCache bool   `json:"noCache"`
	Title   string `json:"title"`
}
type TreeMenuStruct struct {
	Id         int64               `json:"-"`
	ParentId   int64               `json:"-"`
	AlawysShow bool                `json:"alwaysShow"`
	Children   []*TreeMenuChildren `json:"children"`
	Component  string              `json:"component"`
	Hidden     bool                `json:"hidden"`
	Mate       Mate                `json:"meta"`
	Name       string              `json:"name"`
	Path       string              `json:"path"`
	Redirect   string              `json:"redirect"`
}
type TreeMenuChildren struct {
	Component string `json:"component"`
	Hidden    bool   `json:"hidden"`
	Mate      Mate   `json:"meta"`
	Name      string `json:"name"`
	Path      string `json:"path"`
}

func UniqueMenu(items []db_model.Menu) []db_model.Menu {
	idSet := make(map[int]bool)
	var result []db_model.Menu

	for _, item := range items {
		if _, exists := idSet[int(item.MenuId)]; !exists {
			result = append(result, item)
			idSet[int(item.MenuId)] = true
		}
	}
	return result
}

func TreeMenu(items []db_model.Menu) []*TreeMenuStruct {
	nodeMap := make(map[int]*TreeMenuStruct)
	for _, node := range items {
		if node.MenuType == "F" {
			continue
		}
		TreeMenuStruct := &TreeMenuStruct{
			Id:         node.MenuId,
			ParentId:   node.ParentId,
			AlawysShow: true,
			Component:  node.Component,
			Hidden:     false,
			Mate:       Mate{Icon: node.Icon, Link: node.Path, NoCache: false, Title: node.MenuName},
			Name:       node.Path,
			Path:       "/" + node.Path,
			Redirect:   "",
		}
		if node.MenuType == "M" {
			TreeMenuStruct.Component = "Layout"
		}
		if node.IsFrame == 1 {
			TreeMenuStruct.Mate.Link = ""
		}

		titleCase := cases.Title(language.English)
		TreeMenuStruct.Name = titleCase.String(TreeMenuStruct.Name)
		nodeMap[int(node.MenuId)] = TreeMenuStruct
	}
	// 构建树形结构
	var rootNodes []*TreeMenuStruct
	for _, node := range items {
		if node.MenuType == "F" {
			continue
		}

		if node.ParentId == 0 {
			rootNodes = append(rootNodes, nodeMap[int(node.MenuId)])
		} else {
			//子节点
			parentNode := nodeMap[int(node.ParentId)]

			if parentNode != nil {
				treeMenuChildren := &TreeMenuChildren{
					Component: node.Component,
					Hidden:    false,
					Mate:      Mate{Icon: node.Icon, Link: node.Path, NoCache: false, Title: node.MenuName},
					Name:      node.Path,
					Path:      node.Path,
				}
				if node.IsFrame == 1 {
					treeMenuChildren.Mate.Link = ""
				}
				titleCase := cases.Title(language.English)
				treeMenuChildren.Name = titleCase.String(treeMenuChildren.Name)
				parentNode.Children = append(parentNode.Children, treeMenuChildren)
			}

		}
	}
	return rootNodes
}
